﻿using System;
using UnityEngine;

public static class Player
{
    private const int MaxEnergy = 20;
    private const int MaxHitPoints = 10;

    public static Powerup Powerup;
    public static float MaxMovementSpeed = 7.5f;

    public delegate void PlayerDiedEventHandler();
    public static event PlayerDiedEventHandler OnPlayerDied;

    static Player()
    {
        Savegame.OnSavegameLoaded += SavegameOnSavegameLoaded;
        Powerup = new Powerup(CurrentPowerup.None);
        EventManager.OnPlayerReset += EventManagerOnPlayerReset;
    }

    static void EventManagerOnPlayerReset(object sender, PlayerResetEventArgs e)
    {
        Powerup = e.reset.Powerup;
        HitPoints = e.reset.PlayerHp;
        Energy = e.reset.PlayerEnergy;
        Object.transform.position = e.reset.Coordinates;
    }

    public static GameObject Object { get; private set; }
    public static Vector3 StartPosition { get; set; }

    public static int HitPoints { get; private set; }
    public static int Energy { get; private set; }
    public static string Name { get; private set; }

    public static void InitializePlayer(string playerName)
    {
        Name = playerName;
        HitPoints = 5;
        Energy = 10;
    }

    private static void SavegameOnSavegameLoaded(object sender, SavegameLoadedEventArgs e)
    {
        HitPoints = e.PlayerHitPoints;
        Energy = e.PlayerEngergy;
        StartPosition = new Vector3(e.PlayerStartPosition.x, e.PlayerStartPosition.y, e.PlayerStartPosition.z);
        Name = e.PlayerName;
    }

    public static void SetObject(GameObject gObject, object sender)
    {
        if (sender.GetType() == typeof(EventManager))
            Object = gObject;
    }

    public static void AddHitPoints(int amount, object sender)
    {
        if (sender.GetType() == typeof(PlayerManager))
            CalculateHitPoints(amount);
    }

    private static void CalculateHitPoints(int change)
    {
        if (HitPoints + change >= MaxHitPoints)
            HitPoints = MaxHitPoints;
        else if (HitPoints + change <= 0)
        {
            HitPoints = 0;
            if (OnPlayerDied != null)
                OnPlayerDied();
        }
        else
            HitPoints += change;
    }

    public static void AddEnergy(int amount, object sender)
    {
        if (sender.GetType() == typeof(PlayerManager))
            CalculateEnergy(amount);
    }

    private static void CalculateEnergy(int change)
    {
        if (Energy + change >= MaxEnergy)
            Energy = MaxEnergy;
        else if (Energy + change <= 0)
            Energy = 0;
        else
            Energy += change;
    }
}